import requests
from PIL import Image
from io import BytesIO
import base64
import os
import uuid
import time
from fastapi.responses import JSONResponse
from app.setting import settings

class HBImageAPI:
    def __init__(self):
        # 定义静态资源存储路径
        self.static_path = f"{settings.STATIC_PATH}/images"
        self.static_dir = f"{settings.STATIC_DIR}/images"
        # 确保静态资源目录存在
        os.makedirs(self.static_dir, exist_ok=True)
        
    def handle(self, url: str, type: str = "json"):
        try:
            # 下载远程图片
            response = requests.get(url)
            response.raise_for_status()  # 确保请求成功
            
            # 使用PIL打开图片
            img = Image.open(BytesIO(response.content))
            
            # 转换为黑白图片
            img_bw = img.convert('L')
            
            # 根据type参数决定返回类型
            if type.lower() == "json":
                # 将处理后的图片转为base64编码
                buffered = BytesIO()
                img_bw.save(buffered, format="PNG")
                img_str = base64.b64encode(buffered.getvalue()).decode()
                
                return JSONResponse(content={
                    "success": True,
                    "message": "图片已成功转换为黑白",
                    "data": {
                        "image_base64": f"data:image/png;base64,{img_str}"
                    }
                }, status_code=200, media_type="application/json, charset=utf-8")
            elif type.lower() == "image":
                # 生成唯一文件名
                filename = f"{uuid.uuid4().hex}_{int(time.time())}.png"
                file_path = os.path.join(self.static_dir, filename)
                
                # 保存图片到静态资源目录
                img_bw.save(file_path, format="PNG")
                
                # 构建图片URL
                image_url = f"{self.static_path}/{filename}"
                
                return JSONResponse(content={
                    "success": True,
                    "message": "图片已成功转换为黑白",
                    "data": {
                        "image_url": image_url
                    }
                }, status_code=200, media_type="application/json, charset=utf-8")
            else:
                return JSONResponse(content={
                    "success": False,
                    "message": f"不支持的type参数: {type}，支持的类型为json或image",
                    "data": None
                }, status_code=400, media_type="application/json, charset=utf-8")
        except requests.exceptions.RequestException as e:
            return JSONResponse(content={
                "success": False,
                "message": f"获取远程图片失败: {str(e)}",
                "data": None
            }, status_code=500, media_type="application/json, charset=utf-8")
        except Exception as e:
            return JSONResponse(content={
                "success": False,
                "message": f"处理图片时出错: {str(e)}",
                "data": None
            }, status_code=500, media_type="application/json, charset=utf-8")